//
//  CityViewController.m
//  YouMin_iOS
//
//  Created by lanou3g on 15/12/9.
//  Copyright © 2015年 wey. All rights reserved.
//

#import "CityViewController.h"
#import "CityCellModel.h"
#import "CityCell.h"
#import "NetWorkHelper.h"
#import "CityDetailController.h"
@interface CityViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UICollectionViewDelegate>

//获取列表
@property (nonatomic, strong) NSMutableArray *newsArray;
//collectionView
@property (weak, nonatomic) IBOutlet UICollectionView *collectView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;

@end

@implementation CityViewController

- (void)viewWillAppear:(BOOL)animated {
    [self request];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    //设置layout的属性
    [self setLayout];
}

- (void)setLayout {
    //设置Item的大小
    self.flowLayout.itemSize = CGSizeMake(self.view.frame.size.width - 16,320);
    //设置最小行间距
    self.flowLayout.minimumLineSpacing = 12;
    // 设置collectionView的边距(上左下右)
    self.flowLayout.sectionInset = UIEdgeInsetsMake(5, 8, 5, 8);
}

// 解析数据
- (void)request {
    [[NetWorkHelper shareInstance] GET:@"http://api.breadtrip.com/hunter/products/more/?city_name=%E5%8C%97%E4%BA%AC&sign=f6db3c07777859156678d391b7ed717b&start=0" parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSDictionary *dictionary = responseObject;
        NSArray *arr = dictionary[@"product_list"];
        self.newsArray = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            CityCellModel *cellM = [[CityCellModel alloc]init];
            [cellM setValuesForKeysWithDictionary:dic];
            NSDictionary *dic1 = dic[@"user"];
            cellM.avatar_l = dic1[@"avatar_l"];
            [self.newsArray addObject:cellM];
        }
        [self.collectView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

#pragma mark --- Collection View Data Source

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.newsArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CityCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"city_cell" forIndexPath:indexPath];
    cell.cityCells = self.newsArray[indexPath.item];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CityDetailController *cdc = [[CityDetailController alloc]init];
    CityCellModel *cellMod = self.newsArray[indexPath.item];
    cdc.strID = cellMod.product_id;
    [self.navigationController pushViewController:cdc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
